package dao

import (
	"context"
	"github.com/go-redis/redis/v8"
	"icasset/internal/constants"
	"icasset/internal/data"
	"icasset/internal/model"

	"gorm.io/gorm"
)

type GormDemandDAO struct {
	ctx   context.Context
	redis *redis.Client
	db    *gorm.DB
}

func NewGormDemandDAO(db *gorm.DB) *GormDemandDAO {
	return &GormDemandDAO{
		db:    db,
		redis: data.InitRedisClient(),
		ctx:   context.Background(),
	}
}

func (d *GormDemandDAO) GetAllDemands(ctx context.Context) ([]*model.IcDemand, error) {
	var demands []*model.IcDemand
	err := d.db.Find(&demands).Error
	if err != nil {
		return nil, err
	}
	return demands, nil
}

func (d *GormDemandDAO) AddDemand(ctx context.Context, demand *model.IcDemand) error {
	err := d.db.Create(demand).Error
	if err != nil {
		return err
	}
	return nil
}

func (d *GormDemandDAO) GetDemandByPkid(ctx context.Context, pkid int64) (*model.IcDemand, error) {
	var demand model.IcDemand
	err := d.db.Where("pkid = ?", pkid).First(&demand).Error
	if err != nil {
		return nil, err
	}
	return &demand, nil
}

func (d *GormDemandDAO) GetDemandByUserId(ctx context.Context, userId string) ([]*model.IcDemand, error) {
	var demands []*model.IcDemand
	err := d.db.Where("user_id = ?", userId).Find(&demands).Error
	if err != nil {
		return nil, err
	}
	return demands, nil
}

func (d *GormDemandDAO) GetDemandBySellerId(ctx context.Context, sellerId string) ([]*model.IcDemand, error) {
	var demands []*model.IcDemand
	err := d.db.Where("seller_id = ?", sellerId).Find(&demands).Error
	if err != nil {
		return nil, err
	}
	return demands, nil
}

func (d *GormDemandDAO) QueryDemandPage(ctx context.Context, pageNum, pageSize int) {
	//TODO implement me
	panic("implement me")
}

func (d *GormDemandDAO) ConfirmDemandByBuyer(ctx context.Context, Pkid int64, FinalPrice float64, DeadlineTime string) {
	selectedDemand, err := d.GetDemandByPkid(ctx, Pkid)
	if err != nil {
		return
	}
	if selectedDemand.Status == constants.DemandStatusWaiting {
		selectedDemand.FinalPrice = FinalPrice
		selectedDemand.DeadlineTime = DeadlineTime
		selectedDemand.Status = constants.DemandStatusBidding
		d.db.Save(selectedDemand)
	}
}

func (d *GormDemandDAO) CancelDemandByBuyer(ctx context.Context, demand *model.IcDemand) {
	selectedDemand, err := d.GetDemandByPkid(ctx, demand.Pkid)
	if err != nil {
		return
	}
	selectedDemand.CancelReason = demand.CancelReason
	selectedDemand.Status = constants.DemandStatusCanceled
	d.db.Save(selectedDemand)
}
